package com.hfzy.ihk.web.calldata.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.hfzy.ihk.common.facade.enums.call.CommitTo;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.facade.calldata.entity.CallHistory;

import com.hfzy.ihk.web.calldata.biz.CallHistoryBiz;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/callHistory")
public class CallHistoryController {
    static Logger logger = LoggerFactory.getLogger(CallHistoryController.class);

    @Autowired
    CallHistoryBiz callHistoryBiz;

    @CrossOrigin(origins="*")
    @RequestMapping("getCallHistoryPage")
    public String getCallHistoryPage(@RequestParam Map<String, String> paramMap){
        logger.info("http查询通话记录信息,data:{}",JSON.toJSONString(paramMap));
        Map<String,Object> resultMap = new HashMap<>();
        SerializeConfig config = new SerializeConfig();
        try {
            BoolQueryBuilder builder = QueryBuilders.boolQuery();
            if(paramMap.containsKey("whereFrom")&&StringUtil.isNotNull(paramMap.get("whereFrom"))){
                builder.must(QueryBuilders.termQuery("whereFrom.keyword",paramMap.get("whereFrom").toString()));
            }
            if(paramMap.containsKey("customerPhone")&&StringUtil.isNotNull(paramMap.get("customerPhone").toString().trim())){
                builder.must(QueryBuilders.termQuery("mainCallPhone",paramMap.get("customerPhone").toString().trim()));
            }
            if(paramMap.containsKey("userId")&&StringUtil.isNotNull(paramMap.get("userId").toString().trim())){
                builder.must(QueryBuilders.termQuery("createUserId.keyword",paramMap.get("userId").toString().trim()));
            }
            if(paramMap.containsKey("customerName")&&StringUtil.isNotNull(paramMap.get("customerName").toString().trim())){
                builder.must(QueryBuilders.termQuery("customerName",paramMap.get("customerName").toString().trim()));
            }
            if(paramMap.containsKey("customerNo")&&StringUtil.isNotNull(paramMap.get("customerNo").toString().trim())){
                builder.must(QueryBuilders.termQuery("propertyNo",paramMap.get("customerNo").toString().trim()));
            }
            if(paramMap.containsKey("packageType")&&StringUtil.isNotNull(paramMap.get("packageType").toString().trim())){
                builder.must(QueryBuilders.termQuery("packageId",paramMap.get("packageType").toString().trim()));
            }
            if(paramMap.containsKey("callTimeSecondMin")&&StringUtil.isNotNull(paramMap.get("callTimeSecondMin").toString().trim())){
                builder.must(QueryBuilders.rangeQuery("recordTimeLength").gte(paramMap.get("callTimeSecondMin").toString().trim()));
            }
            if(paramMap.containsKey("callTimeSecondMax")&&StringUtil.isNotNull(paramMap.get("callTimeSecondMax").toString().trim())){
                builder.must(QueryBuilders.rangeQuery("recordTimeLength").lte(paramMap.get("callTimeSecondMax").toString().trim()));
            }
            if(paramMap.containsKey("callType")&&StringUtil.isNotNull(paramMap.get("callType").toString().trim())){
                builder.must(QueryBuilders.termQuery("callType",paramMap.get("callType").toString().trim()));
            }
            if(paramMap.containsKey("commitTo")&&StringUtil.isNotNull(paramMap.get("commitTo").toString().trim())){
                builder.must(QueryBuilders.termQuery("commitTo.keyword",paramMap.get("commitTo").toString().trim()));
            }

            if(paramMap.containsKey("objectId")&&StringUtil.isNotNull(paramMap.get("objectId").toString().trim())){
                builder.must(QueryBuilders.termQuery("objectId",paramMap.get("objectId").toString().trim()));
            }

            if(paramMap.containsKey("status")&&StringUtil.isNotNull(paramMap.get("status").toString())){
                BoolQueryBuilder statusBuilder = QueryBuilders.boolQuery();
                if("0".equals(paramMap.get("status").toString())){

                    BoolQueryBuilder boolQueryBuilder0 = QueryBuilders.boolQuery();
                    boolQueryBuilder0.must(QueryBuilders.termsQuery("commitTo.keyword", CommitTo.fromValue("4").name(),CommitTo.fromValue("5").name(),CommitTo.fromValue("8").name()));
                    boolQueryBuilder0.mustNot(QueryBuilders.termQuery("targetCallAnswered","true"));

                    BoolQueryBuilder boolQueryBuilder1 = QueryBuilders.boolQuery();
                    boolQueryBuilder1.mustNot(QueryBuilders.termsQuery("commitTo.keyword", CommitTo.fromValue("4").name(),CommitTo.fromValue("5").name(),CommitTo.fromValue("8").name()));
                    boolQueryBuilder1.mustNot(QueryBuilders.termQuery("mainCallAnswered","true"));
                    statusBuilder.should(boolQueryBuilder0).should(boolQueryBuilder1);
                }else if("1".equals(paramMap.get("status").toString())){

                    BoolQueryBuilder boolQueryBuilder0 = QueryBuilders.boolQuery();
                    boolQueryBuilder0.must(QueryBuilders.termsQuery("commitTo.keyword", CommitTo.fromValue("4").name(),CommitTo.fromValue("8").name()));
                    boolQueryBuilder0.must(QueryBuilders.termQuery("targetCallAnswered","true"));

                    BoolQueryBuilder boolQueryBuilder1 = QueryBuilders.boolQuery();
                    boolQueryBuilder1.mustNot(QueryBuilders.termsQuery("commitTo.keyword", CommitTo.fromValue("4").name(),CommitTo.fromValue("8").name()));
                    boolQueryBuilder1.must(QueryBuilders.termQuery("mainCallAnswered","true"));
                    statusBuilder.should(boolQueryBuilder0).should(boolQueryBuilder1);
                }
                builder.must(statusBuilder);
            }
            if(paramMap.containsKey("sessionId")&&StringUtil.isNotNull(paramMap.get("sessionId").toString().trim())){
                builder.must(QueryBuilders.termQuery("sessionId.keyword",paramMap.get("sessionId").toString().trim()));
            }

            if(StringUtil.isNotNull(paramMap.get("mainCallStartTimeMin"))&&StringUtil.isNotNull(paramMap.get("mainCallStartTimeMax"))) {
                QueryBuilder mainCallStartTime = QueryBuilders.rangeQuery("mainCallStartTime").from(
                        paramMap.get("mainCallStartTimeMin").toString()).to(paramMap.get("mainCallStartTimeMax").toString());
                builder.must(mainCallStartTime);

            }else{
                if(StringUtil.isNotNull(paramMap.get("mainCallStartTimeMin"))) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    QueryBuilder mainCallStartTime = QueryBuilders.rangeQuery("mainCallStartTime").from(
                            paramMap.get("mainCallStartTimeMin").toString()).to(sdf.format(new Date()));
                    builder.must(mainCallStartTime);
                }
                if(StringUtil.isNotNull(paramMap.get("mainCallStartTimeMax"))) {
                    QueryBuilder  mainCallStartTime = QueryBuilders.rangeQuery("mainCallStartTime").from(
                            "1970-01-01 00:00:00").to(paramMap.get("mainCallStartTimeMax").toString());
                    builder.must(mainCallStartTime);
                }
            }

            //额外添加参数
            //分页
            Pageable pageable=PageRequest.of(0,10);
            if(paramMap.containsKey("page")&&paramMap.containsKey("limit")){

                pageable = PageRequest.of(Integer.parseInt(paramMap.get("page").toString())-1, Integer.parseInt(paramMap.get("limit").toString()));
            }
            //排序
            FieldSortBuilder order = SortBuilders.fieldSort("createTime").order(SortOrder.DESC);
            Page<CallHistory> page = callHistoryBiz.queryCallHistoryPageList(builder,order,pageable,null);
            resultMap.put("msg","成功");
            resultMap.put("code",10000);
            resultMap.put("total", page.getTotalElements());
            resultMap.put("data",page.getContent());
            config.configEnumAsJavaBean(CommitTo.class);
        }catch (Exception e){
            logger.error("分页获取通话记录查询出错! data:{},错误信息:{}",paramMap,e);
            e.printStackTrace();
            resultMap.put("msg","失败");
            resultMap.put("code",10001);
        }
        return JSON.toJSONString(resultMap,config);
    }


}
